package me.dz.dreamcleaner.command;

import org.bukkit.command.CommandSender;

import java.lang.reflect.Method;
import java.util.HashMap;

import static me.dz.dreamcleaner.utils.MsgUtils.chat;

public class ICommand {

    private static final HashMap<String, Method> methodMap = new HashMap<>();
    private static final HashMap<String, ECommand> commandMap = new HashMap<>();
    private static final HashMap<String, ICommand> iCommandMap = new HashMap<>();
    private static final HashMap<Integer,String> map = new HashMap<>();

    public ICommand(){
        register(this.getClass().getDeclaredMethods());
    }

    public void register(Method[] methods){
        for (Method method : methods){
            ECommand command = method.getAnnotation(ECommand.class);
            if (command != null){
                String order = command.order().toLowerCase();
                map.put(command.id(),order);
                methodMap.put(order,method);
                commandMap.put(order,command);
                iCommandMap.put(order,this);
            }
        }
    }

    public static void help(CommandSender sender,String label){
        chat(sender,"&6DreamCleaner帮助页面");
        int i = map.size();
        int n = 0;
        while (true){
            if (map.containsKey(n)){
                String key = map.get(n);
                ECommand eCommand = getECommand(key);
                if (eCommand != null){
                    if (sender.isOp() || !eCommand.op()){
                        chat(sender,label,eCommand.order() + " " + eCommand.desc());
                    }
                }
                i--;
                if (i == 0)break;
            }
            n++;
        }
        if (sender.isOp()){
            chat(sender,"&c注意:&7[是否异步] 填写true/false 不填则默认");
        }
    }

    public static ICommand getICommand(String key){
        key = key.toLowerCase();
        if (iCommandMap.containsKey(key)){
            return iCommandMap.get(key);
        }
        return null;
    }

    public static Method getMethod(String key){
        key = key.toLowerCase();
        if (methodMap.containsKey(key)){
            return methodMap.get(key);
        }
        return null;
    }

    public static ECommand getECommand(String key){
        key = key.toLowerCase();
        if (commandMap.containsKey(key)){
            return commandMap.get(key);
        }
        return null;
    }
}
